﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Xml.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

namespace TestHiddenColumns.ListDefinition1
{
	public partial class viewpage : WebPartPage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			HideColumns();
		}
		private void HideColumns()
		{
			XsltListViewWebPart viewCtrl = Controls.FindControlsRecursively<XsltListViewWebPart>().FirstOrDefault();
			if (null == viewCtrl) return;
			using (StringReader sr = new StringReader(viewCtrl.XmlDefinition))
			{
				XDocument xd = XDocument.Load(sr);
				var xFields = xd.Descendants("FieldRef").Where(x => UserCanSeeColumn(x)).ToList();
				xd.Descendants("FieldRef").Remove();
				xd.Descendants("ViewFields").FirstOrDefault().Add(xFields);
				viewCtrl.XmlDefinition = xd.ToString();
			}
		}
		private bool UserCanSeeColumn(XElement column)
		{
			if (null == column) return true;
			XAttribute xa = column.Attribute("Name");
			if(null == xa) return true;
			string columnName = column.Attribute("Name").Value;//columnName represents the INTERNALNAME of the column
			if (string.IsNullOrEmpty(columnName)) return true;
			if (0 == string.Compare(columnName, "Column3") && !SPContext.Current.Web.CurrentUser.IsSiteAdmin) return false;// show Column3 only to the site admin
			return true;
		}
	}
}